package com.example.demo.level5;


import com.github.shyiko.mysql.binlog.BinaryLogFileReader;
import com.github.shyiko.mysql.binlog.event.Event;
import com.github.shyiko.mysql.binlog.event.TableMapEventData;
import com.github.shyiko.mysql.binlog.event.deserialization.ChecksumType;
import com.github.shyiko.mysql.binlog.event.deserialization.EventDeserializer;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


public class ReadBinlog {

    @SneakyThrows
    public static void main(String[] args) {

        String filePath = "D:\\project\\tmp\\binlog.000002";
        File binlogFile = new File(filePath);
        EventDeserializer eventDeserializer = new EventDeserializer();
        eventDeserializer.setChecksumType(ChecksumType.CRC32);
        BinaryLogFileReader reader = new BinaryLogFileReader(binlogFile,
                eventDeserializer);
        try {
            // 准备写入的文件名称
            /*
             * File f1 = new File("D:\\mysql-bin.000845.sql"); if
             * (f1.exists()==false){ f1.getParentFile().mkdirs(); }
             */
            FileOutputStream fos = new FileOutputStream(
                    filePath + ".sql", true);
            for (Event event; (event = reader.readEvent()) != null; ) {
                System.out.println(event.toString());
                // 把数据写入到输出流
                fos.write(event.toString().getBytes());
            }
            // 关闭输出流
            fos.close();
            System.out.println("输入完成");
        } finally {
            reader.close();
        }
    }


}
